<template>
	<view class="landlord-box">
		<view class="topic-nav">
			<image :src="$imgUrl + '/personal/back-icon.png'" class="image" @click="back" mode=""></image>
			<view class="view">委托出租</view>
			<image :src="$imgUrl + '/personal/back-icon.png'" class="image" style="visibility: hidden;" mode=""></image>
		</view>
		<view class="lan-content">
			<view class="landlord-nav">
				<view class="land-nav-left">出租数：<span>{{form.leaseNum || 0}}</span></view>
				<view class="land-nav-right" @click="goIndex">
					<span>我是租客</span>
					<image :src="$imgUrl + '/personal/back-personal-icon.png'" mode=""></image>
				</view>
			</view>
			<view class="landlord-detail">
				<view class="view">
					<view class="lan-c1">{{Number(form.receivedRent).toFixed(2)}}</view>
					<view class="lan-c2">已收租金额（元）</view>
				</view>
				<view class="view">
					<view class="lan-c1">{{Number(form.notReceivedRent).toFixed(2)}}</view>
					<view class="lan-c2">待收租金额（元）</view>
				</view>
			</view>
			<view class="landlord-con">
				<scroll-view
					scroll-y="true"
					refresher-enabled="true"
					@refresherrefresh="onRefresh"
					@scrolltolower="loadMore"
					style="height: 100%;"
					:refresher-triggered="isRefreshing">
					<view style="padding-bottom: 20rpx;">
						<view
							v-if="form.dataList&&form.dataList.length > 0" 
							class="faq-list-item" 
							v-for="(item, index) in form.dataList" 
							:key="index">
							<view class="landlord-list">
								<view class="lan-title flex">
									<view class="title flex-1 line1">{{item.roomName}}</view>
									<view class="look" @click="goOwnerContract(item)">查看合同<uni-icons color="#999" size="14" type="right" /></view>
								</view>
								<view class="lan-list-row">
									<view class="lan-list-col-l view">
										<span>{{timestamp(item.nextCollectionDate)}}</span>
										<span>下次收款日期</span>
									</view>
									<view class="lan-list-col-r view">
										<span>{{item.orderPeriods || '--'}}期</span>
										<span>账单周期</span>
									</view>
								</view>
								<!-- <view class="lan-list-row">
									<view class="lan-list-col-l view">
										<span>{{item.liveStatus}}</span>
										<span>入住状态</span>
									</view>
									<view class="lan-list-col-r view">
										<span>{{item.currentLiveNum}}人</span>
										<span>当前入住人数</span>
									</view>
								</view> -->
								<view class="lan-list-row">
									<view class="lan-list-col-l view">
										<span>{{timestamp(item.startTime)}}</span>
										<span>业主合同开始时间</span>
									</view>
									<view class="lan-list-col-r view">
										<span>{{timestamp(item.endTime)}}</span>
										<span>业主合同结束时间</span>
									</view>
								</view>
							</view>
						</view>
					</view>
				</scroll-view>
			</view>
		</view>
	</view>
</template>

<script setup lang="ts">
import { getRentInfo, getOwnerRoom } from '@/common/API/landlord'
import { downLoadLandlordElectronic } from '@/common/API/contract'
import { onLoad, onUnload } from "@dcloudio/uni-app"
import { reactive,ref } from "vue"
import dayjs  from "dayjs"

const isRefreshing= ref(false)
const isLoadMore = ref(false)
const flag = ref(false)

const form = reactive({
	leaseNum: null,
	receivedRent: null,
	notReceivedRent: null,
	pageSize: 10,
	pageNo: 1,
	page: 1,
	dataList: []
})
const back = () => {
	uni.navigateBack({
		delta: 1
	});
}
const goIndex = () => {
	uni.switchTab({
		url:'/pages/personal/index'
	})
}
//跳转业主合同
const goOwnerContract = async (item) => {
	let p = await downLoadLandlordElectronic(item.ownerContractId)
	if(p){
		// #ifdef MP-WEIXIN
		uni.downloadFile({
			url: p.downloadUrl,
			success: (res) => {
				if (res.statusCode === 200) {
					uni.saveFile({
						tempFilePath: res.tempFilePath,
						success: (res1) => {
						  var savedFilePath = res1.savedFilePath;
						  if(savedFilePath){
							wx.openDocument({
								filePath: res1.savedFilePath, 
								showMenu: true,
								fileType: "pdf",
								success: function (res2) {
									console.log('打开PDF成功');
								},
								fail:function(err){
									console.log(err)
								}
							})
						  }
						},fail: err2 => {
							console.log(err2)
						}
					})
				}
			},
			fail:(err1) => {
				console.log(err1)
			}
		});
		// #endif
		
		// #ifdef APP-PLUS
		 uni.downloadFile({
		   url: p.downloadUrl,
		   success: res => {
		     console.log(res)
		     if (res.statusCode === 200) {
		       uni.saveFile({
		         tempFilePath: res.tempFilePath,
		         success:res2 => {
					uni.openDocument({
						filePath: res2.savedFilePath, 
						showMenu: true,
						fileType: "pdf",
						success: function (res3) {
							console.log('打开PDF成功');
						},
						fail: function (err) {
							if(err.errCode == 1 || err.code == 1){
								// uni.showToast({
								// 	title: `未找到能打开PDF类型文件的手机应用`,
								// 	icon: 'none'
								// })
								uni.navigateTo({
									url: `/pages/personal/contract/web-view?url=${encodeURIComponent(p.downloadUrl)}`
								})
							}
						}
					})
		         },
		         fail: e => {
				  console.log(e)
		           uni.showToast({
		             title: "保存失败，请稍后重试！",
		             icon: "none"
		           })
		         }
		       })
		     }
		   },fail:err=>{
			   console.log(err)
		   }
		 })
		 // #endif
	}
}
//处理时间戳
const timestamp = (val:any,s) => {
	if(val){
		return !s ? dayjs(val).format('YYYY-MM-DD') : dayjs(val).format('YYYY-MM-DD HH:mm:ss')
	}else{
		return '--'
	}
}
//获取房东房屋租金信息
const getRentList = async () => {
	let res = await getRentInfo()
	if(res){
		form.leaseNum = res.leaseNum
		form.receivedRent = res.receivedRent
		form.notReceivedRent = res.notReceivedRent
	}
}
//获取房东房屋租金信息
const getOwnerList = async () => {
	uni.showLoading({
		title:'加载中...'
	});
	let data = {
		pageNo: form.pageNo,
		pageSize: form.pageSize
	}
	let res = await getOwnerRoom(data)
	if(res){
		form.page = res.total? Math.ceil(res.total/form.pageSize) : 1
		if(form.pageNo==1) form.dataList = []
		form.dataList = form.dataList.concat(res.list)
	}
	uni.hideLoading()
}
onLoad((options)=>{
	getRentList()
	getOwnerList()
	if (options) {
		flag.value = options.flag
	}
})
//下拉刷新
const onRefresh = () => {
	form.pageNo = 1
	form.pageSize = 10
	isRefreshing.value = true;
	getOwnerList()
	getRentList()
	setTimeout(() => {
	    isRefreshing.value = false;
	    uni.stopPullDownRefresh()
	}, 800)
}
//加载更多
const loadMore = () => {
	console.log('上拉加载更多')
	if(form.pageNo >= form.page){
		return
	}
	form.pageNo ++
	isLoadMore.value = true;
	getOwnerList()
	setTimeout(() => {
		isLoadMore.value = false;
	}, 2000)
}
onUnload(() => {
	console.log('onUnload')
	if (!flag.value) {
		uni.switchTab({
		    url: '/pages/personal/index',
		})  
	}
})
</script>
<style>
page{
	height: 100vh;
	background: linear-gradient(180deg, rgba(252, 210, 102, 0.2) 0%, rgba(255, 88, 107, 0) 100%) no-repeat;
	background-size: 750rpx 600rpx;
}
</style>
<style lang="scss" scoped>
	.landlord-box{
		display: flex;
		flex-direction: column;
		height: 100%;
		.topic-nav{
			display: flex;
			align-items: center;
			justify-content: space-around;
			padding-bottom: constant(safe-area-inset-bottom);
			padding-bottom: env(safe-area-inset-bottom);
			padding-top: constant(safe-area-inset-top);
			padding-top: env(safe-area-inset-top);
			height: var(–status-bar-height);
			padding-top: calc(var(--status-bar-height) + 28rpx);
			.image{
				width: 17rpx;
				height: 31rpx;
				padding: 0 32rpx;
			}
			.view{
				flex: 1;
				text-align: center;
				font-size: 34rpx;
			}
		}
		.lan-content{
			flex: 1;
			display: flex;
			flex-direction: column;
			overflow: hidden;
		}
		.landlord-nav{
			display: flex;
			justify-content: space-between;
			margin: 84rpx 0 24rpx 0;
			.land-nav-left{
				font-size: 36rpx;
				color: rgba(55, 61, 39, 1);
				font-weight: bold;
				margin-left: 58rpx;
				span{
					color: rgba(253, 150, 24, 1);
				}
			}
			.land-nav-right{
				color: #fff;
				width: 176rpx;
				height: 54rpx;
				border-radius: 28rpx 0px 0px 28rpx;
				background: rgba(253, 150, 24, 0.68);
				display: flex;
				align-items: center;
				justify-content: center;
				font-size: 24rpx;
				image{
					width: 13rpx;
					height: 22rpx;
					margin-left: 10rpx;
				}
			}
		}
		.landlord-detail{
			width: 686rpx;
			height: 156rpx;
			margin: 32rpx auto;
			border-radius: 10rpx;
			background: linear-gradient(180deg, rgba(254, 232, 185, 1) 0%, rgba(244, 211, 152, 1) 100%);
			box-shadow: 0px 6rpx 32rpx  rgba(0, 0, 0, 0.03);
			display: flex;
			align-items: center;
			.view{
				flex: 1;
			}
			.lan-c1{
				font-size: 30rpx;
				color: rgba(81, 44, 25, 1);
				text-align: center;
			}
			.lan-c2{
				font-size: 26rpx;
				color: rgba(147, 110, 76, 1);
				text-align: center;
			}
		}
		.landlord-con{
			flex: 1;
			overflow: hidden;
		}
		.landlord-list{
			margin: 0 32rpx 24rpx 32rpx;
			border-radius: 12rpx;
			background: rgba(255, 255, 255, 1);
			box-shadow: 0px 6rpx 32rpx  rgba(0, 0, 0, 0.03);
			padding-bottom: 26rpx;
			.lan-title{
				padding: 40rpx 32rpx 14rpx 32rpx;
				font-size: 32rpx;
				color: rgba(77, 77, 77, 1);
				.title{
					font-size: 32rpx;
				}
				.look{
					color: #999;
					margin-left: 20rpx;
				}
			}
			.lan-list-row{
				display: flex;
				margin: 28rpx 44rpx;
				.view{
					flex: 1;
					&>span:nth-child(1){
						color: rgba(0, 0, 0, 1);
						font-size: 36rpx;
						font-weight: bold;
					}
					&>span:nth-child(2){
						color: rgba(150, 150, 150, 1);
						font-size: 24rpx;
					}
				}
				.lan-list-col-l{
					border-right: 1px solid rgba(238, 238, 238, 1);
					display: flex;
					flex-direction: column;
					padding-left: 32rpx;
				}
				.lan-list-col-r{
					display: flex;
					flex-direction: column;
					padding-left: 76rpx;
				}
			}
		}
	}
</style>